import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:go_router/go_router.dart';
import 'package:hinge/common/values/icon.dart';
import 'package:hinge/store/root_store.dart';
import 'package:hinge/common/models/chat_message_model.dart';
import 'package:hinge/common/models/user_model.dart';
import 'package:hinge/common/services/user_service.dart';

class ChatPage extends StatefulWidget {
  final String chatId;
  const ChatPage({super.key, required this.chatId});

  @override
  State<ChatPage> createState() => _ChatPageState();
}

class _ChatPageState extends State<ChatPage> {
  late final rootStore = RootStore();
  late final chatStore = rootStore.chatStore;
  UserModel? currentUser;
  TextEditingController _controller = TextEditingController();
  ScrollController _scrollController = ScrollController(); // 添加滚动控制器

  // 滚动到底部的方法
  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  void initState() {
    super.initState();
    chatStore.loadChatDetail(widget.chatId).then((_) {
      // 加载完成后滚动到底部
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _scrollToBottom();
      });
    });
    currentUser = UserService.getCurrentUser();
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose(); // 释放滚动控制器
    super.dispose();
  }

  // 处理用户头像点击
  void _handleAvatarTap(UserModel user) {
    // 如果是当前用户，直接跳转到个人中心
    final currentUser = UserService.getCurrentUser();
    if (currentUser != null && user.id == currentUser.id) {
      context.push('/personal');
    } else {
      // 否则跳转到指定用户的个人中心
      context.push('/personal/${user.id}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Observer(
        builder: (_) {
          if (chatStore.isLoading) {
            return const Center(child: CircularProgressIndicator());
          }
          return Container(
            decoration: BoxDecoration(
              gradient: LinearGradient(
                begin: Alignment.topCenter,
                end: Alignment.bottomCenter,
                colors: [const Color(0xFFC4B4FD), const Color(0xFFEFE0FF)],
              ),
            ),
            child: SafeArea(
              bottom: false,
              child: Column(
                children: [
                  SizedBox(height: 10.h),
                  Row(
                    children: [
                      SizedBox(width: 20.w),
                      GestureDetector(
                        onTap: () {
                          // 使用明确的 GoRouter 方法
                          final router = GoRouter.of(context);
                          if (router.canPop()) {
                            router.pop();
                          } else {
                            // 如果不能返回，则导航到首页
                            router.go('/');
                          }
                        },
                        child: Icon(
                          IconFont.back,
                          color: Colors.white,
                          size: 28.w,
                        ),
                      ),
                      SizedBox(width: 10.w),
                      Text(
                        'Chat',
                        style: TextStyle(color: Colors.white, fontSize: 20.sp),
                      ),
                      const Spacer(),
                      Icon(IconFont.report, color: Colors.white, size: 28.w),
                      SizedBox(width: 20.w),
                    ],
                  ),
                  SizedBox(height: 28.h),
                  // 群成员头像横向滚动
                  SizedBox(
                    height: 52.h,
                    child: ListView.separated(
                      scrollDirection: Axis.horizontal,
                      padding: EdgeInsets.symmetric(horizontal: 20.w),
                      itemCount: chatStore.chatMembers.length,
                      separatorBuilder: (_, __) => SizedBox(width: 16),
                      itemBuilder: (context, index) {
                        final UserModel user = chatStore.chatMembers[index];
                        return Column(
                          children: [
                            GestureDetector(
                              onTap: () => _handleAvatarTap(user),
                              child: CircleAvatar(
                                radius: 26.w,
                                backgroundImage: AssetImage(user.avatar),
                              ),
                            ),
                          ],
                        );
                      },
                    ),
                  ),
                  SizedBox(height: 40.h),
                  // 消息列表
                  Expanded(
                    child: ListView.builder(
                      controller: _scrollController, // 添加滚动控制器
                      padding: EdgeInsets.symmetric(horizontal: 24.w),
                      itemCount: chatStore.chatMessages.length,
                      itemBuilder: (context, index) {
                        final ChatMessageModel msg =
                            chatStore.chatMessages[index];
                        final sender = chatStore.chatMembers.firstWhere(
                          (u) => u.id == msg.senderId,
                          orElse:
                              () => UserModel(
                                id: 0,
                                account: '',
                                password: '',
                                nickname: 'Unknown',
                                avatar: '',
                              ),
                        );
                        final isMe =
                            currentUser != null &&
                            msg.senderId == currentUser!.id;
                        return Container(
                          margin: EdgeInsets.only(bottom: 20.h),
                          child: Row(
                            mainAxisAlignment:
                                isMe
                                    ? MainAxisAlignment.end
                                    : MainAxisAlignment.start,
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children:
                                isMe
                                    ? [
                                      // 右侧：内容、头像
                                      Flexible(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.end,
                                          children: [
                                            GestureDetector(
                                              onTap:
                                                  () =>
                                                      _handleAvatarTap(sender),
                                              child: CircleAvatar(
                                                radius: 24.w,
                                                backgroundImage:
                                                    sender.avatar.isNotEmpty
                                                        ? AssetImage(
                                                          sender.avatar,
                                                        )
                                                        : null,
                                                child:
                                                    sender.avatar.isEmpty
                                                        ? const Icon(
                                                          Icons.person,
                                                        )
                                                        : null,
                                              ),
                                            ),
                                            SizedBox(height: 8.h),
                                            _buildMessageBubble(
                                              msg,
                                              sender,
                                              isMe,
                                            ),
                                          ],
                                        ),
                                      ),
                                    ]
                                    : [
                                      // 左侧：头像、内容
                                      Flexible(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.start,
                                          children: [
                                            GestureDetector(
                                              onTap:
                                                  () =>
                                                      _handleAvatarTap(sender),
                                              child: CircleAvatar(
                                                radius: 24.w,
                                                backgroundImage:
                                                    sender.avatar.isNotEmpty
                                                        ? AssetImage(
                                                          sender.avatar,
                                                        )
                                                        : null,
                                                child:
                                                    sender.avatar.isEmpty
                                                        ? const Icon(
                                                          Icons.person,
                                                        )
                                                        : null,
                                              ),
                                            ),
                                            SizedBox(height: 8.h),
                                            _buildMessageBubble(
                                              msg,
                                              sender,
                                              isMe,
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                          ),
                        );
                      },
                    ),
                  ),
                  // 底部输入框
                  Container(
                    padding: EdgeInsets.fromLTRB(16.w, 8.h, 16.w, 30.h),
                    color: Colors.transparent,
                    child: Stack(
                      alignment: Alignment.centerRight,
                      children: [
                        Container(
                          padding: EdgeInsets.only(right: 44.w),
                          decoration: BoxDecoration(
                            color: Colors.black.withOpacity(0.3),
                            borderRadius: BorderRadius.circular(24.w),
                          ),
                          child: TextField(
                            controller: _controller,
                            decoration: InputDecoration(
                              border: InputBorder.none,
                              hintText: 'Say something...',
                              hintStyle: TextStyle(
                                fontSize: 15.sp,
                                color: Colors.white,
                                fontFamily: 'Inter',
                              ),
                              contentPadding: EdgeInsets.symmetric(
                                horizontal: 16.w,
                                vertical: 12.h,
                              ),
                            ),

                            style: TextStyle(
                              fontSize: 15.sp,
                              color: Colors.white,
                              fontFamily: 'Inter',
                            ),
                          ),
                        ),
                        Positioned(
                          right: 16.w,
                          child: GestureDetector(
                            onTap: () {
                              // 发送消息
                              if (_controller.text.trim().isNotEmpty) {
                                chatStore.sendMessage(_controller.text);
                                _controller.clear(); // 清空输入框
                                // 发送消息后滚动到底部
                                WidgetsBinding.instance.addPostFrameCallback((
                                  _,
                                ) {
                                  _scrollToBottom();
                                });
                              }
                            },
                            child: Icon(
                              IconFont.send,
                              color: Colors.white,
                              size: 22.w,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          );
        },
      ),
    );
  }

  Widget _buildMessageBubble(
    ChatMessageModel msg,
    UserModel sender,
    bool isMe,
  ) {
    if (msg.type == MessageType.text) {
      return Container(
        padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 10.h),
        decoration: BoxDecoration(
          color: isMe ? Color(0xFFDBBFFF) : Color(0xFFBD88FF),
          borderRadius:
              isMe
                  ? BorderRadius.only(
                    topRight: Radius.circular(0.w),
                    topLeft: Radius.circular(20.w),
                    bottomLeft: Radius.circular(20.w),
                    bottomRight: Radius.circular(20.w),
                  )
                  : BorderRadius.only(
                    topLeft: Radius.circular(0.w),
                    topRight: Radius.circular(20.w),
                    bottomLeft: Radius.circular(20.w),
                    bottomRight: Radius.circular(20.w),
                  ),
        ),
        child: Text(
          msg.text ?? '',
          style: TextStyle(
            fontSize: 14.sp,
            height: 2, // 添加行高，使多行文本有适当的间距
            color: Colors.white,
            fontFamily: 'Inter',
          ),
        ),
      );
    } else if (msg.type == MessageType.perfumeCard && msg.perfumeCard != null) {
      return Stack(
        alignment: Alignment.bottomCenter,
        children: [
          ClipRRect(
            borderRadius:
                isMe
                    ? BorderRadius.only(
                      topRight: Radius.circular(0.w),
                      topLeft: Radius.circular(20.w),
                      bottomLeft: Radius.circular(20.w),
                      bottomRight: Radius.circular(20.w),
                    )
                    : BorderRadius.only(
                      topLeft: Radius.circular(0.w),
                      topRight: Radius.circular(20.w),
                      bottomLeft: Radius.circular(20.w),
                      bottomRight: Radius.circular(20.w),
                    ),
            child: Image.asset(
              msg.perfumeCard!.url,
              width: 166.w,
              height: 166.w,
              fit: BoxFit.cover,
            ),
          ),
          Positioned(
            bottom: 10.w,
            child: ElevatedButton(
              onPressed: () {
                // TODO: go 按钮点击逻辑
              },
              style: ElevatedButton.styleFrom(
                backgroundColor: const Color(0xFFBE88FF),
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20.w),
                ),
                padding: EdgeInsets.symmetric(horizontal: 28.w, vertical: 8.h),
                elevation: 0,
              ),
              child: Text(
                'GO',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 16.sp,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
          ),
        ],
      );
    } else {
      return const SizedBox();
    }
  }
}
